#!/usr/bin/env python
#-*-coding:utf-8-*-

# runsingle.py is part of "lemon-py" (http://code.google.com/p/lemon-py/).
# Copyright (C) 2010  - JBC <JBC dot Develop at gmail dot com >

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Based on code:
#   - http://code.activestate.com/recipes/546512/
#   - http://code.activestate.com/recipes/474070/

# Love u Flor <3


################################################################################
# DOCS
################################################################################

"""App for mantain not more than one instance of an app runnning"""


################################################################################
# META
################################################################################

__prj__ = "singleinstance.py (lemon-py)"
__version__ = "0.1"
__license__ = "GPL3"
__author__ = "JBC"
__since__ = "0.1"
__date__ = "2010-06-23"
__copyright__ = "%s %s Copyright (C) %s %s" % (__prj__, __version__,
                                               __date__, __author__)


################################################################################
# IMPORTS
################################################################################

import sys
import subprocess
import shlex
import optparse
import os

import singleinstance

################################################################################
# CONSTANS
################################################################################

SHLEX_POSIX = os.name in ("posix",)
 

################################################################################
# STAND ALONE APP FUNCTION
################################################################################

def _get_parser():
    
    usage = __doc__ + "\n\n"
    
    usage += "usage:\n\t$python %prog <option, [option3...option n]> <command>"
    
    epilog = "This program comes with ABSOLUTELY NO WARRANTY." + \
             "This is free software, and you are welcome to redistribute it" + \
             "under certain conditions; for details see LICENSE.txt."
             
    parser = optparse.OptionParser(usage, version=__version__, epilog=epilog)
    
    parser.add_option("-m", "--mutex",
                      type="string",
                      action="store",
                      dest="mutex",
                      help="An string for identificate your app (Windows)",
                      metavar="STRING")
    parser.add_option("-p", "--pidpath",
                      action="store",
                      type="string",
                      dest="pidpath",
                      help="pid file path (Posix)",
                      metavar="FILE")
    return parser


def _main():
      
    # parse all the params
    parser = _get_parser()
    opts, args = parser.parse_args()
    
    try:
        
        #charge the params for the get_loc function in a dict
        kwargs = {}
        if opts.pidpath:
            kwargs["pidpath"] = opts.pidpath
        if opts.mutex:
            kwargs["mutex"] = opts.mutex
        
        # get the locker.
        # Not delete the locker when your singleinstance app is running
        lock = singleinstance.get_lock(**kwargs)
    
    except KeyError, err:
        
        # This code happens when you not give a correct params for this platform
        msg = "%s platform need option(s) '%s'" % (os.name, ",".join(err.args))
        parser.error(msg)
   
    else:
        try:
            
            # Unit all arguments as only one command
            cmd = " ".join(args)
            
            # Verify if the app is running
            if not lock.isrunning():
                
                cmd_parsed = shlex.split(cmd, posix=SHLEX_POSIX)
                sys.exit(subprocess.call(cmd_parsed))
            
            else:
                print """'%s' already running.""" % cmd
        except Exception, err:
            parser.error(str(err))

                
################################################################################
# MAIN
################################################################################

if __name__ == "__main__":
    _main()

